package com.strawcom.charmring.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;

/**
 * display data information after exercise
 * 
 * @author WangPeng
 */
public class Loading1View extends View {

	private final Paint paint = new Paint();

	private int mWidth, mHeight;
	private int color1, color2;
	private float radius1, radius2;
	private final int count = 5;
	private int index = 0;
	private float spacing;
	private float centerX1, centerY;

	public Loading1View(Context context) {
		this(context, null);
	}

	public Loading1View(Context context, AttributeSet attrs) {
		super(context, attrs);
		setLayerType(LAYER_TYPE_SOFTWARE, null);

		color1 = 0xff0451ad;
		color2 = 0xff0980e8;
	}

	@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int widthSize = MeasureSpec.getSize(widthMeasureSpec);
		int heightSize = (int) (widthSize / (count * 1.5f));
		setMeasuredDimension(widthSize, heightSize);
	}

	@Override protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		stopAnim();
	}

	@Override protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		mWidth = w;
		mHeight = h;

		radius1 = mHeight / 2;
		radius2 = radius1 * 0.6f;

		centerY = mHeight / 2;
		centerX1 = radius1;

		spacing = (mWidth - radius1 * 2) * 1f / (count - 1);
	}

	@Override protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		paint.setAntiAlias(true);

		for (int i = 0; i < count; i++) {
			paint.setColor(i == index ? color1 : color2);
			final float radius = i == index ? radius1 : radius2;
			canvas.drawCircle(centerX1 + i * spacing, centerY, radius, paint);
		}

		paint.reset();
	}

	private Handler handler = new Handler();

	public void startAmin() {
		handler.removeCallbacks(runnable);
		handler.post(runnable);
	}

	public void stopAnim() {
		handler.removeCallbacks(runnable);
	}

	private Runnable runnable = new Runnable() {
		@Override public void run() {
			index++;
			if (index >= count) {
				index = 0;
			}
			invalidate();
			handler.postDelayed(runnable, 1000);
		}
	};
}
